package logic

import (
	"context"
	"fmt"
	"math/rand"
	"time"
	"yzy5.21wrk/Models"
	Pkg "yzy5.21wrk/pkg/Sms"

	"yzy5.21wrk/user_srv/internal/svc"
	"yzy5.21wrk/user_srv/user_srv"

	"github.com/zeromicro/go-zero/core/logx"
)

type SmsCaptchaLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSmsCaptchaLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SmsCaptchaLogic {
	return &SmsCaptchaLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SmsCaptchaLogic) SmsCaptcha(in *user_srv.SmsCaptchaRequest) (*user_srv.SmsCaptchaResponse, error) {
	// todo: add your logic here and delete this line
	key := fmt.Sprintf("%s", in.Phone)
	code := fmt.Sprintf("%d", rand.Intn(9000)+1000)
	captcha, err := Pkg.SmsCaptcha(in.Phone, code, "")
	if err != nil {
		return nil, err
	}
	if *captcha.Body.Code != "OK" {
		return nil, fmt.Errorf("captcha code is %s", *captcha.Body.Message)
	}
	Models.RDB.Set(Models.Ctx, key, code, 5*time.Minute)
	return &user_srv.SmsCaptchaResponse{}, nil
}
